import { nextTick, onMounted, onUnmounted, Ref } from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash-es";

/**
 * ECharts钩子函数
 * 用于快速创建、配置和管理ECharts实例
 *
 * @param chartRef DOM引用
 * @param theme ECharts主题，默认为空
 * @returns ECharts实例和工具函数
 */
export function useECharts(
  chartRef: Ref<HTMLElement | null>,
  theme: string = ""
) {
  // ECharts实例
  let chartInstance: echarts.ECharts | null = null;

  // 初始化图表
  const initChart = () => {
    if (!chartRef.value) return;

    // 销毁旧实例
    if (chartInstance) {
      chartInstance.dispose();
    }

    try {
      // 创建新实例
      chartInstance = echarts.init(chartRef.value, theme);
    } catch (e) {
      console.error("初始化图表失败:", e);
    }
  };

  // 处理窗口大小变化
  const resizeHandler = debounce(() => {
    if (chartInstance) {
      chartInstance.resize();
    }
  }, 300);

  // 设置图表选项
  const setOption = (option: echarts.EChartsOption, clear: boolean = true) => {
    if (!chartInstance) {
      initChart();
    }

    if (chartInstance) {
      if (clear) {
        chartInstance.clear();
      }
      chartInstance.setOption(option);
      // 确保图表正确渲染
      setTimeout(() => {
        if (chartInstance) {
          chartInstance.resize();
        }
      }, 50);
    }
  };

  // 获取图表实例 (适用于需要更高级自定义功能时)
  const getInstance = () => {
    if (!chartInstance) {
      initChart();
    }
    return chartInstance;
  };

  // 强制重新渲染图表
  const forceRender = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  // 组件挂载时初始化
  onMounted(() => {
    // 延迟初始化，确保DOM已完全渲染
    setTimeout(() => {
      initChart();
      window.addEventListener("resize", resizeHandler);

      // 触发一次resize事件，确保图表能够正确显示
      setTimeout(() => {
        if (chartInstance) {
          chartInstance.resize();
        }
      }, 200);
    }, 300);
  });

  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener("resize", resizeHandler);
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  });

  // 返回实例和方法
  return {
    setOption,
    getInstance,
    forceRender
  };
} 